package net.oschina.aibinxiao.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.oschina.aibinxiao.domain.User;
import net.oschina.aibinxiao.service.UserService;
import net.oschina.aibinxiao.service.impl.UserServiceImpl;
import net.oschina.aibinxiao.util.SHAEncryptUtil;

/**
 * 用户注册的Servlet
 */
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 接收数据
		// 处理中文乱码
		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String nickname = request.getParameter("nickname");
		String email = request.getParameter("email");
		// 封装数据
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setNickname(nickname);
		user.setEmail(email);
		user.setState(0); // 0：未激活， 1：已激活
		String code = SHAEncryptUtil.SHA256(email); // 将用户email加密后做成激活码
		user.setCode(code);
		user.setRegisterTime(new Date());
		// 调用业务层处理数据
		UserService userService = new UserServiceImpl();
		userService.regist(user);
		// 页面跳转
		request.setAttribute("msg", "您已经注册成功！请前往邮箱激活！");
		request.getRequestDispatcher("/msg.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
